<?php

// NO direct access
defined( '_VALID_MOS' ) or die( 'Restricted access' );

$_MAMBOTS->registerFunction( 'onPrepareContent', 'botDocMan' );

function botDocMan( $published, &$row, &$params, $page=0 ) {
    global $database, $_MAMBOTS;
    
    if ( strpos( $row->text, 'botdocman' ) === false ) {
        return true;
    }
    
    $regex = '/{botdocman\s*id\s*=\s*([0-9]+)\s*}/i'; 

    if (!$published ) {
        $row->text = preg_replace( $regex, '', $row->text );
        return true;
    }
    
    preg_match_all( $regex, $row->text, $matches );

    if ( !isset($_MAMBOTS->_content_mambot_params['botdocman']) ) {
        $query = "SELECT params"
        . "\n FROM #__mambots"
        . "\n WHERE element = 'botdocman'"
        . "\n AND folder = 'content'"
        ;
        $database->setQuery( $query );
        $database->loadObject($mambot);
        
        $_MAMBOTS->_content_mambot_params['botdocman'] = $mambot;
    }

    $mambot = $_MAMBOTS->_content_mambot_params['botdocman'];
    
    $botParams = new mosParameters( $mambot->params );

    
    $GLOBALS['botDocMan_URL'] = $botParams->get( 'urlregister', 'index.php?option=com_registration&task=register' );
    
    $row->text = preg_replace_callback( $regex, 'botDocMan_replacer', $row->text );
    return true;

}


function botDocMan_replacer( &$matches ) {
    global $database, $my;

    $query = "SELECT dmname"
    . "\n FROM #__docman"
    . "\n WHERE id = '{$matches[1]}'";
    $database->setQuery( $query );
    $database->loadObject($document);

    $encodedURL = encodeResource($matches[1]);
    
    if ($my->id){
        $link = '<a href="index.php?resource='.$encodedURL.'" >'.$document->dmname.'</a>';
    }else{
        $link = '<a href="'.$GLOBALS['botDocMan_URL'].'" target="_blank">'.$document->dmname.'</a>';
    }
    
    return $link;
}

function encodeResource($documentID){
    global   $mainframe;
    
    $encodedURL = 'document='.$documentID;
    $encodedURL = base64_encode($encodedURL);
    $encodedURL = $mainframe->_session->session_id.$encodedURL;
    $encodedURL = base64_encode($encodedURL);
    
    return $encodedURL;
}
?>
